import axios from 'axios'
import { message as M } from 'antd'
import { createBrowserHistory } from 'history'

const history = createBrowserHistory()
const service = axios.create({
  baseURL: import.meta.env.BASE_URL,
  timeout: 15000
})

service.interceptors.request.use(
  (config) => {
    if (config.headers != null) {
      const token = localStorage.getItem('token')
      config.headers.Authorization = token !== null ? `Bearer ${token}` : ''
    }
    return config
  },
  async (err) => {
    await M.error('请求失败')
    return Promise.reject(err)
  }
)

service.interceptors.response.use(
  async (response) => {
    const { code, data, message } = response.data
    if (code === 200) {
      return data
    } else if (code === 401) {
      history.replace('/login')
      localStorage.removeItem('token')
      window.location.reload()
    } else {
      await M.error(message)
      return Promise.reject(response)
    }
  },
  async (err) => {
    await M.error('服务器响应失败')
    return Promise.reject(err)
  }
)

export default service
